package com.xge.commponet_chat

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.alibaba.android.arouter.utils.TextUtils
import com.blankj.utilcode.util.ToastUtils
import com.xge.common_libary.http.ApiResult
import com.xge.common_libary.utils.copyToClipboard
import com.xge.commponet_chat.databinding.FragmentChatBinding
import com.xge.commponet_chat.vm.WChatViewModel

class ChatFragment : Fragment() {

    private val viewModel: WChatViewModel by viewModels()
    private lateinit var binding: FragmentChatBinding
    private var content = ""

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        binding = FragmentChatBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        viewModel.pyqInfo()
        viewModel.pyqInfo.observe(this.viewLifecycleOwner) { result ->
            when (result) {
                is ApiResult.Error -> ToastUtils.showShort(result.message)
                is ApiResult.Exception -> ToastUtils.showShort(result.exception)
                is ApiResult.Success -> {
                    content = result.data.content?: ""
                    binding.tvContent.text = result.data.content
                    binding.tvAuthor.text = "-- ${result.data.source}"
                }
            }
        }

        binding.tvChange.setOnClickListener {
            viewModel.pyqInfo()
        }

        binding.tvContent.setOnClickListener {
            if(!TextUtils.isEmpty(content)){
                copyToClipboard(requireContext(),content)
            }
        }
        binding.tvShare.setOnClickListener {
            shareTextToSystem(content)
        }
    }

    fun shareTextToSystem(text: String) {
        val intent = Intent(Intent.ACTION_SEND)
        intent.type = "text/plain"
        intent.putExtra(Intent.EXTRA_TEXT, text)

        val chooser = Intent.createChooser(intent, "分享到")
        // 注意：如果没有匹配的 App 会崩溃，所以建议加判断
        if (intent.resolveActivity(requireContext().packageManager) != null) {
            requireContext().startActivity(chooser)
        } else {
            Toast.makeText(context, "没有可用的分享应用", Toast.LENGTH_SHORT).show()
        }
    }

    companion object {
        fun newInstance(): ChatFragment = ChatFragment()
    }
}
